<?php
/**
 * 点大商城（www.diandashop.com） - 微信公众号小程序商城系统!
 * Copyright © 2020 山东点大网络科技有限公司 保留所有权利
 * =========================================================
 * 版本：V2
 * 授权主体：shop.guanjunbang.cn
 * 授权域名：shop.guanjunbang.cn
 * 授权码：vdcajlVLIVAgVdkfJvgY
 * ----------------------------------------------
 * 您只能在商业授权范围内使用，不可二次转售、分发、分享、传播
 * 任何企业和个人不得对代码以任何目的任何形式的再发布
 * =========================================================
 */

// +----------------------------------------------------------------------
// | 后台账号 子账号
// +----------------------------------------------------------------------
namespace app\controller;
use think\facade\View;
use think\facade\Db;
use app\model\Member as m;
class Member extends Common
{
    public function initialize(){
		parent::initialize();
		//if(bid > 0) showmsg('无访问权限');
	}
	//会员列表
    public function index(){
		$levelArr = Db::name('member_level')->where('aid',aid)->order('sort,id')->column('name','id');
		$defaultCat = Db::name('member_level_category')->where('aid',aid)->where('isdefault', 1)->value('id');
		if($defaultCat > 0) {
            $levelIdsDefault = Db::name('member_level')->where('aid',aid)->where('cid', $defaultCat)->column('id');
        }
		if(request()->isAjax()){
			$page = input('param.page');
			$limit = input('param.limit');
			if(input('param.field') && input('param.order')){
				$order = input('param.field').' '.input('param.order');
			}else{
				$order = 'id desc'; 
			}
			$where = [];
			$where[] = ['aid','=',aid];
			if(input('param.mid')) {
                if(false){}else{
                    $where[] = ['id','=',input('param.mid')];
                }
            }else{
                if(false){}else{
                    if(input('param.card_id')) {
                        $mids = Db::name('membercard_record')->where('aid',aid)->where('card_id',input('param.card_id'))->column('mid');
                        $where[] = ['id','in',$mids];
                    }
                }
            }

			if(input('param.pid')) $where[] = ['pid','=',input('param.pid')];
			if(input('param.isgetcard')){
				if(input('param.isgetcard') == 1){
					$where[] = ['','exp',Db::raw('card_code is not null')];
				}else{
					$where[] = ['','exp',Db::raw('card_code is null')];
				}
			}
			if(input('param.nickname')) $where[] = ['nickname|tel|realname','like','%'.input('param.nickname').'%'];
			if(input('param.realname')) $where[] = ['realname','like','%'.input('param.realname').'%'];
			if(input('param.levelid')) {
			    if($levelIdsDefault && !in_array(input('param.levelid'),$levelIdsDefault)) {
                    $mids = Db::name('member_level_record')->where('aid',aid)->where('levelid', input('param.levelid'))->column('mid');
                    $where[] = ['id','in',$mids];
                } else
                    $where[] = ['levelid','=',input('param.levelid')];
            }

			//其他分组等级的筛选

			if(input('param.ctime') ){
				$ctime = explode(' ~ ',input('param.ctime'));
				$where[] = ['createtime','>=',strtotime($ctime[0])];
				$where[] = ['createtime','<',strtotime($ctime[1]) + 86400];
			}

			if(input('param.fhid')){
				$midlist = Db::name('shop_order_fenhong')->where('aid',aid)->where('id',input('param.fhid'))->value('midlist');
				$where[] = ['id','in',$midlist];
			}
            if(input('param.fxmid')){
				$fxmid = input('param.fxmid/d');
				if(input('param.deep') == 1){
					$where[] = ['pid','=',$fxmid];
				}elseif(input('param.deep') == 2){
					$where[] = Db::raw("pid in(select id from ".table_name('member')." where pid=".$fxmid.")");
				}elseif(input('param.deep') == 3){
					$where[] = Db::raw("pid in(select id from ".table_name('member')." where pid in(select id from ".table_name('member')." where pid=".$fxmid."))");
				}
			}

			$count = 0 + Db::name('member')->where($where)->count();
			$data = Db::name('member')->where($where)->page($page,$limit)->order($order)->select()->toArray();

            foreach($data as $k=>$v){

                $data[$k]['levelname'] = $levelArr[$v['levelid']];
				if($v['pid']){
					$parent = Db::name('member')->where('aid',aid)->where('id',$v['pid'])->find();
				}else{
					$parent = array();
				}
                $data[$k]['parent'] = $parent;
                $data[$k]['money'] = \app\common\Member::getmoney($v);
                $data[$k]['score'] = \app\common\Member::getscore($v);

				}
			return json(['code'=>0,'msg'=>'查询成功','count'=>$count,'data'=>$data,'role'=>$role]);
		}

		if($this->auth_data == 'all' || in_array('Member/*',$this->auth_data) || in_array('Member/recharge',$this->auth_data)){
			$haverechargeAuth = true;
		}else{
			$haverechargeAuth = false;
		}
		if($this->auth_data == 'all' || in_array('Member/*',$this->auth_data) || in_array('Member/addscore',$this->auth_data)){
			$haveaddscoreAuth = true;
		}else{
			$haveaddscoreAuth = false;
		}
		if($this->auth_data == 'all' || in_array('Member/*',$this->auth_data) || in_array('Member/addcommission',$this->auth_data)){
			$haveaaddcommissionAuth = true;
		}else{
			$haveaaddcommissionAuth = false;
		}
        if(false){}else{
            $haveaddyuanbaoAuth = false;
        }

		View::assign('aid',aid);
		View::assign('levelArr',$levelArr);
		$sort = true;
        $adminset = Db::name('admin_set')->where('aid',aid)->find();

        View::assign('haverechargeAuth',$haverechargeAuth);
        View::assign('haveaddscoreAuth',$haveaddscoreAuth);
        View::assign('haveaaddcommissionAuth',$haveaaddcommissionAuth);
        View::assign('haveaddyuanbaoAuth',$haveaddyuanbaoAuth);
        View::assign('sort',$sort);
        View::assign('adminset',$adminset);
        return View::fetch();
    }
	//导出
	public function excel(){
		$levelList = Db::name('member_level')->where('aid',aid)->select()->toArray();
		$levelArr = array();
		foreach($levelList as $v){
			$levelArr[$v['id']] = $v['name'];
		}

		if(input('param.field') && input('param.order')){
			$order = input('param.field').' '.input('param.order');
		}else{
			$order = 'id desc';
		}
		$where = [];
		$where[] = ['aid','=',aid];
		if(input('param.mid')) $where[] = ['id','=',input('param.mid')];
		if(input('param.pid')) $where[] = ['pid','=',input('param.pid')];
		if(input('param.isgetcard')){
			if(input('param.isgetcard') == 1){
				$where[] = ['','exp',Db::raw('card_code is not null')];
			}else{
				$where[] = ['','exp',Db::raw('card_code is null')];
			}
		}
		if(input('param.nickname')) $where[] = ['nickname|tel|realname','like','%'.input('param.nickname').'%'];
		if(input('param.realname')) $where[] = ['realname','like','%'.input('param.realname').'%'];
		if(input('param.levelid')) $where[] = ['levelid','=',input('param.levelid')];
		if(input('param.ctime') ){
			$ctime = explode(' ~ ',input('param.ctime'));
			$where[] = ['createtime','>=',strtotime($ctime[0])];
			$where[] = ['createtime','<',strtotime($ctime[1]) + 86400];
		}

		if(input('param.fhid')){
			$midlist = Db::name('shop_order_fenhong')->where('aid',aid)->where('id',input('param.fhid'))->value('midlist');
			$where[] = ['id','in',$midlist];
		}

        if(input('param.fxmid')){
			$fxmid = input('param.fxmid/d');
			if(input('param.deep') == 1){
				$where[] = ['pid','=',$fxmid];
			}elseif(input('param.deep') == 2){
				$where[] = Db::raw("pid in(select id from ".table_name('member')." where pid=".$fxmid.")");
			}elseif(input('param.deep') == 3){
				$where[] = Db::raw("pid in(select id from ".table_name('member')." where pid in(select id from ".table_name('member')." where pid=".$fxmid."))");
			}
		}

		$list = Db::name('member')->where($where)->order($order)->select()->toArray();
        if(false){}else{
            $title = array('ID','头像','昵称','来源','省份','城市','姓名','电话',t('余额'),t('积分'),t('佣金'),'等级','加入时间','关注状态','公众号openid','小程序openid');
        }
        $data = array();
		foreach($list as $k=>$vo){
			if($vo['platform']=='wx'){
				$vo['platform'] = '小程序';
			}elseif($vo['platform']=='mp'){
				$vo['platform'] = '公众号';
			}elseif($vo['platform']=='h5'){
				$vo['platform'] = 'H5';
			}
			if($vo['subscribe']==1){
				$vo['subscribe'] = '已关注';
			}else{
				$vo['subscribe'] = '未关注';
			}
            $vo['money'] = \app\common\Member::getmoney($vo);
            $vo['score'] = \app\common\Member::getscore($vo);
			$vo['levelname'] = $levelArr[$vo['levelid']];
            if(false){}else if(false){}else if(false){}else{
                $data[] = array($vo['id'],$vo['headimg'],$vo['nickname'],$vo['platform'],$vo['province'],$vo['city'],$vo['realname'],$vo['tel'],$vo['money'],$vo['score'],$vo['commission'],$vo['levelname'],date('Y-m-d H:i',$vo['createtime']),$vo['subscribe'],$vo['mpopenid'],$vo['wxopenid']);
            }
		}
		$this->export_excel($title,$data);
	}
	//导入
	public function importexcel(){
		set_time_limit(0);
		ini_set('memory_limit',-1);
		$file = input('post.file');
		$exceldata = $this->import_excel($file);
		$levelList = Db::name('member_level')->where('aid',aid)->select()->toArray();
		$levelArr = array();
		foreach($levelList as $v){
			$levelArr[$v['name']] = $v['id'];
		}
		$defaultlevel = Db::name('member_level')->where('aid',aid)->where('isdefault',1)->find();

		$insertnum = 0;
		$updatenum = 0;
		foreach($exceldata as $data){
			$indata = [];
			$indata['headimg'] = $data[0] ? $data[0] : PRE_URL.'/static/img/touxiang.png';
			$indata['nickname'] = preg_replace('/[\x{10000}-\x{10FFFF}]/u', ' ', $data[1]);
			$indata['platform'] = $this->getplatform(trim($data[2]));
			$indata['province'] = trim($data[3]);
			$indata['city'] = trim($data[4]);
			$indata['realname'] = trim($data[5]);
			$indata['tel'] = trim($data[6]);
			$indata['money'] = trim($data[7]);
			$indata['score'] = trim($data[8]);
			$indata['commission'] = trim($data[9]);
			$indata['levelid'] = $levelArr[$data[10]] ? $levelArr[$data[10]] : $defaultlevel['name'];
			$indata['subscribe'] = ($data[11] == '已关注' ? 1 : 0);
			$indata['mpopenid'] = trim($data[12]);
            $indata['wxopenid'] = trim($data[13]);
			if($data[14] && trim($data[14])!=''){
				$indata['pwd'] = md5(trim($data[14]));
			}
			$member = [];
			if(!$member && $indata['wxopenid']){
				$member = Db::name('member')->where('aid',aid)->where('wxopenid',$indata['wxopenid'])->find();
			}
			if(!$member && $indata['mpopenid']){
				$member = Db::name('member')->where('aid',aid)->where('mpopenid',$indata['mpopenid'])->find();
			}
			if(!$member && $indata['tel']){
				$member = Db::name('member')->where('aid',aid)->where('tel',$indata['tel'])->find();
			}
			if($indata['money'] === '') unset($indata['money']);
			if($indata['score'] === '') unset($indata['score']);
			if($indata['commission'] === '') unset($indata['commission']);
			if($indata['mpopenid'] == '') unset($indata['mpopenid']);
			if($indata['wxopenid'] == '') unset($indata['wxopenid']);
			if($indata['tel'] == '') unset($indata['tel']);
			if($member){
				if($indata['headimg'] == PRE_URL.'/static/img/touxiang.png') unset($indata['headimg']);
				if($indata['nickname'] == '') unset($indata['nickname']);
				if($indata['platform'] == '') unset($indata['platform']);
				if($indata['province'] == '') unset($indata['province']);
				if($indata['city'] == '') unset($indata['city']);
				if($indata['realname'] == '') unset($indata['realname']);
				if($indata['tel'] == '') unset($indata['tel']);
				if($indata['levelid'] == '') unset($indata['levelid']);
				if($indata['subscribe'] == '') unset($indata['subscribe']);
				if(false){}else{
					Db::name('member')->where('aid',aid)->where('id',$member['id'])->update($indata);
				}
				$updatenum++;
			}else{
				if(false){}else{		
					$indata['aid'] = aid;
					$indata['sex'] = 3;
					$indata['createtime'] = time();
					Db::name('member')->insert($indata);
				}
				$insertnum++;
			}
		}
		\app\common\System::plog('导入会员');
		return json(['status'=>1,'msg'=>'成功新增'.$insertnum.'条数据，修改'.$updatenum.'条数据']);
	}
	public function getplatform($str){
		if($str == '公众号'){
			return 'mp';
		}elseif($str == '小程序'){
			return 'wx';
		}elseif($str == 'H5'){
			return 'h5';
		}else{
			return $str;
		}
	}
	//会员充值
	public function recharge(){
		$mid = input('post.rechargemid/d');
		$money = floatval(input('post.rechargemoney'));
		$actionname = '充值';
		if($money == 0 || $money == ''){
			return json(['status'=>0,'msg'=>'请输入金额']);
		}
		if($money < 0) $actionname = '扣费';
		if(session('IS_ADMIN')==0){
			$user = Db::name('admin_user')->where('aid',aid)->where('id',$this->uid)->find();
			$remark = '商家'.$actionname.'，操作员：'.$user['un'];
		}else{
			$remark = '商家'.$actionname;
		}
		$rs = \app\common\Member::addmoney(aid,$mid,$money,$remark);
		\app\common\System::plog('给会员'.$mid.$actionname.'，金额'.$money);
		if($rs['status']==0) return json($rs);
		return json(['status'=>1,'msg'=>$actionname.'成功']);
	}
	//充值积分
	public function addscore(){
		$mid = input('post.id/d');
		$score = intval(input('post.score'));
		$remark = input('post.remark');
        $actionname = '增加';
		if($score == 0){
			return json(['status'=>0,'msg'=>'请输入'.t('积分').'数']);
		}
        if($score < 0) $actionname = '扣除';
		$rs = \app\common\Member::addscore(aid,$mid,$score,'后台修改：'.$remark);
		\app\common\System::plog('给会员'.$mid.$actionname.'积分'.$score);
		if($rs['status']==0) return json($rs);
		return json(['status'=>1,'msg'=>'操作成功']);
	}
	//加佣金
	public function addcommission(){
		$mid = input('post.id/d');
		$commission = floatval(input('post.commission'));
		$remark = input('post.remark');
        $actionname = '增加';
		if($commission == 0){
			return json(['status'=>0,'msg'=>'请输入'.t('佣金').'金额']);
		}
        if($commission < 0) $actionname = '扣除';
		$rs = \app\common\Member::addcommission(aid,$mid,0,$commission,'后台修改：'.$remark,0);
		\app\common\System::plog('给会员'.$mid.$actionname.t('佣金').$commission);
		if($rs['status']==0) return json($rs);
		return json(['status'=>1,'msg'=>'操作成功']);
	}
	//编辑
	public function edit(){
		if(input('param.id')){
			$info = Db::name('member')->where('aid',aid)->where('id',input('param.id/d'))->find();
            $info['money'] = \app\common\Member::getmoney($info);
            $info['score'] = \app\common\Member::getscore($info);
		}else{
			$info = array('id'=>'');
		}
		$level_cid = Db::name('member_level_category')->where('aid',aid)->where('isdefault',1)->value('id');
        $level_cid = $level_cid ? $level_cid : 0;
		$levelList = Db::name('member_level')->where('aid',aid)->where('cid', $level_cid)->order('sort')->select()->toArray();
		$defaultlevel = Db::name('member_level')->where('aid',aid)->where('isdefault',1)->find();
		$levelArr = Db::name('member_level')->where('aid',aid)->order('sort')->column('name,areafenhong','id');
		View::assign('defaultlevel',$defaultlevel);
		View::assign('info',$info);
		View::assign('levelList',$levelList);
		View::assign('levelArr',$levelArr);
		$blist = Db::name('business')->field('id,name')->where('aid',aid)->order('sort desc,id')->select()->toArray();
        View::assign('blist',$blist);
        return View::fetch();
	}
	//保存
	public function save(){
		$info = input('post.info/a');
		$defaultlevel = Db::name('member_level')->where('aid',aid)->where('isdefault',1)->find();
		if($info['levelid'] == $defaultlevel['id'] || input('post.levelcq') == 1){
			$info['levelendtime'] = 0;
		}else{
			$info['levelendtime'] = strtotime($info['levelendtime']);
		}
		if($info['pwd']){
			$info['pwd'] = md5($info['pwd']);
		}else{
			unset($info['pwd']);
		}
       

		if($info['id']){
			$rs = m::edit(aid,$info);
			if($rs['status'] == 0) return json($rs);
			\app\common\System::plog('编辑会员'.$info['id']);
		}else{
			$info['aid'] = aid;
			$info['createtime'] = time();
            $info['id'] = m::add(aid,$info);
			\app\common\System::plog('添加会员'.$info['id']);
		}

        return json(['status'=>1,'msg'=>'操作成功','url'=>(string)url('index')]);
	}
	//会员删除
	public function del(){
		$ids = input('post.ids/a');
		m::del(aid,$ids);
		\app\common\System::plog('删除会员'.implode(',',$ids));
		return json(['status'=>1,'msg'=>'删除成功']);
	}
	//会员审核
	public function setst(){
		$id = input('post.id/d');
		$st = input('post.st/d');
		$checkreason = input('post.checkreason');
		$member = Db::name('member')->where('id',$id)->where('aid',aid)->find();
		if(!$member) return json(['status'=>0,'msg'=>'未找到该用户']);
		Db::name('member')->where('id',$id)->where('aid',aid)->update(['checkst'=>$st,'checkreason'=>$checkreason]);
		if($st == 1){
			$rs = \app\common\Sms::send(aid,$member['tel'],'tmpl_checksuccess',[]);
		}elseif($st == 2){
			$rs = \app\common\Sms::send(aid,$member['tel'],'tmpl_checkerror',['reason'=>$checkreason]);
		}
		
		//审核结果通知
		$tmplcontent = [];
		$tmplcontent['first'] = ($st == 1 ? '恭喜您的注册审核通过' : '抱歉您的注册未审核通过');
		$tmplcontent['remark'] = ($st == 1 ? '' : ($checkreason.'，')) .'请点击查看详情~';
		$tmplcontent['keyword1'] = '用户注册';
		$tmplcontent['keyword2'] = ($st == 1 ? '已通过' : '未通过');
		$tmplcontent['keyword3'] = date('Y年m月d日 H:i');
		\app\common\Wechat::sendtmpl(aid,$id,'tmpl_shenhe',$tmplcontent,m_url('pages/my/usercenter'));
		//订阅消息
		$tmplcontent = [];
		$tmplcontent['thing8'] = '用户注册';
		$tmplcontent['phrase2'] = ($st == 1 ? '已通过' : '未通过');
		$tmplcontent['thing4'] = $checkreason;
		
		$tmplcontentnew = [];
		$tmplcontentnew['thing2'] = '用户注册';
		$tmplcontentnew['phrase1'] = ($st == 1 ? '已通过' : '未通过');
		$tmplcontentnew['thing5'] = $checkreason;
		\app\common\Wechat::sendwxtmpl(aid,$id,'tmpl_shenhe',$tmplcontentnew,'pages/my/usercenter',$tmplcontent);

		return json(['status'=>1,'msg'=>'操作成功','res'=>$rs]);
	}
	//冻结 解冻
	public function setfreeze(){
		$id = input('post.id/d');
		$st = input('post.st/d');
		$member = Db::name('member')->where('id',$id)->where('aid',aid)->find();
		if(!$member) return json(['status'=>0,'msg'=>'未找到该用户']);
		Db::name('member')->where('id',$id)->where('aid',aid)->update(['isfreeze'=>$st]);
		return json(['status'=>1,'msg'=>'操作成功']);
	}
	//会员卡详情
	public function getcarddetail(){
		$card_id = input('post.card_id');
		$card_code = input('post.card_code');
		$info = Db::name('membercard_record')->where('aid',aid)->where('card_id',$card_id)->where('card_code',$card_code)->find();
		return json(['status'=>1,'data'=>$info]);
	}
	//更新用户的unionid 仅支持公众号 不支持小程序
	public function updateunionid(){
		$platform = input('param.platform');
		if(!$platform) $platform = 'mp';
		$url = 'https://api.weixin.qq.com/cgi-bin/user/info/batchget?access_token='.\app\common\Wechat::access_token(aid,$platform);
		$memberlist = Db::name('member')->field('id,mpopenid,unionid,headimg,nickname')->where('aid',aid)->where("mpopenid!='' and mpopenid is not null")->select()->toArray();
		$user_list = [];
		$thismemberlist = [];
		foreach($memberlist as $k=>$member){
			$user_list[] = ['openid'=>$member['mpopenid'],'lang'=>'zh_CN'];
			$thismemberlist[$member['mpopenid']] = $member;
			if(count($user_list) >= 100 || $k+1 == count($memberlist)){
				$rs = curl_post($url,jsonEncode(['user_list'=>$user_list]));
				$rs = json_decode($rs,true);
				if($rs['errcode']!=0 && $rs['errcode']!=1){
					return json(['status'=>0,'msg'=>\app\common\Wechat::geterror($rs)]);
				}
				$user_info_list = $rs['user_info_list'];
				foreach($user_info_list as $k2=>$v2){
					$thismember = $thismemberlist[$v2['openid']];
					if($v2['unionid'] && $v2['unionid'] != $thismember['unionid']){
						Db::name('member')->where('aid',aid)->where('id',$thismember['id'])->update(['unionid'=>$v2['unionid']]);
						echo "ID:{$thismember['id']}，昵称:{$thismember['nickname']} unionid已更新:{$v2['unionid']}<br>";
					}
				}
				$user_list = [];
				$thismemberlist = [];
			}
		}
		die('success');
	}

	private $deeplevel = 0;
	//关系图
	public function charts(){
		$mid = input('param.mid/d');
		$member = Db::name('member')->field('id,nickname,headimg,pid,realname,tel,levelid')->where('aid',aid)->where('id',$mid)->find();
		$leveldata = Db::name('member_level')->where('aid',aid)->order('sort,id')->column('id,sort,name','id');
		if($member){
			$member['children'] = $this->getdown($mid,0,$leveldata);
			$member['downcount'] = count($member['children']);
			$member['name'] = $member['nickname'] . "\r\n" .$leveldata[$member['levelid']]['name'].'(ID:'.$member['id'].' 下级:'.$member['downcount'].'人)';
			View::assign('member',$member);
			View::assign('deeplevel',$this->deeplevel);
		}
		return View::fetch();
	}

	//充值赠送
    public function registerGive()
    {
        if(request()->isPost()){
            $info = input('post.info/a');
            if($info['id']){
                Db::name('register_giveset')->where('aid',aid)->where('id',$info['id'])->update($info);
                \app\common\System::plog('编辑注册赠送'.$info['id']);
            }else{
                $info['aid'] = aid;
                $info['createtime'] = time();
                $id = Db::name('register_giveset')->insertGetId($info);
                \app\common\System::plog('编辑注册赠送'.$id);
            }
            return json(['status'=>1,'msg'=>'操作成功','url'=>(string)url('registerGive')]);
        }

        $info = Db::name('register_giveset')->where('aid',aid)->find();
        if($info) {
            $coupon_ids = explode(',', $info['coupon_ids']);
            $couponList = Db::name('coupon')->where('aid',aid)->where('bid', 0)->whereIn('id', $coupon_ids)->select()->toArray();
        }
        View::assign('couponList',$couponList);
        View::assign('info',$info);

        return View::fetch();
    }

	private function getdown($mid,$deeplevel,$leveldata){
		if($deeplevel > 20) return json([]);
		$deeplevel++;
		$memberlist = Db::name('member')->field('id,nickname,headimg,pid,realname,tel,levelid')->where('aid',aid)->where('pid',$mid)->select()->toArray();
		foreach($memberlist as $k=>$member){
			$memberlist[$k]['children'] = $this->getdown($member['id'],$deeplevel,$leveldata);
			$memberlist[$k]['downcount'] = count($memberlist[$k]['children']);
			$memberlist[$k]['name'] = $member['nickname'] . "\r\n" . $leveldata[$member['levelid']]['name'].'(ID:'.$member['id'].' 下级:'.$memberlist[$k]['downcount'].'人)';
		}
		if($this->deeplevel < $deeplevel) $this->deeplevel = $deeplevel;
		return $memberlist;
	}


	//会员path
	public function updatepath(){
		$memberlist = Db::name('member')->where('aid',aid)->order('id')->select()->toArray();
		foreach($memberlist as $member){
			$pathArr = $this->getpath($member,$path=[]);
			if($pathArr){
				$pathArr = array_reverse($pathArr);
				$pathstr = implode(',',$pathArr);
				Db::name('member')->where('aid',aid)->where('id',$member['id'])->update(['path'=>$pathstr]);
				//var_dump($member['id'].'----'.$pathstr);
				if($member['path'] != $pathstr){
					var_dump($member['path'].'----'.$pathstr);
				}
			}else{
				Db::name('member')->where('aid',aid)->where('id',$member['id'])->update(['path'=>'']);
			}
		}
		die('success');
	}
	public function getpath($member,$path,$deep=1){
		if($member['pid'] && $deep < 10){
			if(in_array($member['pid'],$path)) return $path;
			$path[] = $member['pid'];
			$parent = Db::name('member')->where('aid',aid)->where('id',$member['pid'])->find();
			$deep = $deep + 1;
			return $this->getpath($parent,$path,$deep);
		}
		return $path;
	}

	//增加开团次数
	public function addktnum(){
		$mid = input('post.ktmid/d');
		$ktnum = floatval(input('post.ktnum'));
		if($ktnum == 0){
			return json(['status'=>0,'msg'=>'请输入开团次数']);
		}
		if(session('IS_ADMIN')==0){
			$user = Db::name('admin_user')->where('aid',aid)->where('id',$this->uid)->find();
			$remark = '商家充值，操作员：'.$user['un'];
		}else{
			$remark = '商家充值';
		}
		$member = Db::name('member')->where('aid',aid)->where('id',$mid)->find();
        if(!$member) return ['status'=>0,'msg'=>t('会员').'不存在'];
		$after = $member['ktnum'] + $ktnum;
        Db::name('member')->where('aid',aid)->where('id',$mid)->update(['ktnum'=>$after]);
		\app\common\System::plog('给会员'.$mid.'增加开团次数'.$ktnum);
		return json(['status'=>1,'msg'=>'操作成功']);
	}

    //设置余额宝提现天数
    public function setywtime(){
        $mid = input('post.ywtmid/d');

        $ywrate = input('post.ywrate');
        $ywtime = input('post.ywtime/d');

        if(session('IS_ADMIN')==0){
            $user = Db::name('admin_user')->where('aid',aid)->where('id',$this->uid)->find();
            $remark = '商家设置'.t('余额宝').'提现天数，操作员：'.$user['un'];
        }else{
            $remark = '商家设置'.t('余额宝').'提现天数';
        }
        $member = Db::name('member')->where('aid',aid)->where('id',$mid)->find();
        if(!$member) return ['status'=>0,'msg'=>t('会员').'不存在'];

        Db::name('member')->where('aid',aid)->where('id',$mid)->update(['yuebao_rate'=>$ywrate,'yuebao_withdraw_time'=>$ywtime]);
        \app\common\System::plog('给会员'.$mid.'设置'.t('余额宝').'收益率、提现天数'.$ywtime);
        return json(['status'=>1,'msg'=>'操作成功']);
    }
 	//充值元宝
    public function addyuanbao(){
        if(false){}else{
            return json(['status'=>0,'msg'=>'操作失败']);
        }
    }
	
	//锁定
	public function dolock(){
		if(session('IS_ADMIN') == 0) return json(['status'=>1,'msg'=>'无权限操作']);
		$id = input('post.id/d');
		$st = input('post.st/d');
		Db::name('member')->where('aid',aid)->where('id',$id)->update(['islock'=>$st]);
		return json(['status'=>1,'msg'=>'操作成功']);
	}

    public function choosemember(){
        if(request()->isPost()){
            $data = Db::name('member')->where('aid',aid)->where('bid',bid)->where('id',input('post.id/d'))->find();
            return json(['status'=>1,'msg'=>'查询成功','data'=>$data]);
        }
        return View::fetch();
    }

    //加其他余额
    public function addOtherMoney(){
        }
}
